import OSS from 'ali-oss'
import { v4 as uuidv4 } from 'uuid'
import path from 'path'
import { logger } from '../services/logger'

// 验证OSS配置
const validateOSSConfig = () => {
    const required = {
        region: process.env.OSS_REGION,
        accessKeyId: process.env.OSS_ACCESS_KEY_ID,
        accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
        bucket: process.env.OSS_BUCKET
    }

    const missing = Object.entries(required)
        .filter(([_, value]) => !value)
        .map(([key]) => key)

    if (missing.length > 0) {
        throw new Error(`Missing required OSS configuration: ${missing.join(', ')}`)
    }

    return {
        ...required,
        endpoint: process.env.OSS_ENDPOINT,
        secure: true
    } as OSS.Options
}

// 创建 OSS 客户端
const client = new OSS(validateOSSConfig())

// 上传文件到 OSS
export const uploadToOSS = async (file: Express.Multer.File): Promise<string> => {
    try {
        // 生成文件名
        const ext = path.extname(file.originalname)
        const filename = `uploads/${uuidv4()}${ext}`

        // 上传文件
        const result = await client.put(filename, file.buffer)

        logger.info('File uploaded to OSS', {
            filename,
            size: file.size,
            mimetype: file.mimetype
        })

        return result.url
    } catch (error) {
        logger.error('OSS upload error:', error)
        throw new Error('文件上传失败')
    }
}

// 从 OSS 删除文件
export const deleteFromOSS = async (url: string): Promise<void> => {
    try {
        // 从 URL 中提取文件名
        const filename = url.split('/').pop()
        if (!filename) throw new Error('Invalid file URL')

        // 删除文件
        await client.delete(`uploads/${filename}`)

        logger.info('File deleted from OSS', { filename })
    } catch (error) {
        logger.error('OSS delete error:', error)
        throw new Error('文件删除失败')
    }
}

// 获取文件临时访问 URL
export const getTemporaryUrl = async (url: string): Promise<string> => {
    try {
        // 从 URL 中提取文件名
        const filename = url.split('/').pop()
        if (!filename) throw new Error('Invalid file URL')

        // 生成临时访问 URL（默认有效期 1 小时）
        const result = await client.signatureUrl(`uploads/${filename}`, {
            expires: 3600,
            process: 'image/resize,w_1920' // 可选：限制图片最大宽度
        })

        logger.debug('Generated temporary URL', { filename })
        return result
    } catch (error) {
        logger.error('OSS signature error:', error)
        throw new Error('获取临时访问链接失败')
    }
} 